import React, { PureComponent } from 'react';
import { message } from 'antd';
import { ContentPackage, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, ModalC } from '../../../comps';
import moment from 'moment';
import OperateForm from './newOperateForm';
import { connect } from 'dva';

@connect(({ BaselineInformationNewM, loading }) => ({ BaselineInformationNewM, loading }))
export default class BaselineInformationNew extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectBaselineType: [
        { value: '单一', title: '单一' },
        { value: '自定义', title: '自定义' },
        { value: '复合', title: '复合' },
        { value: '市值加权', title: '市值加权' },
      ], // 基准类型下拉
      searchObj: {},
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      currentUser: {}, // 判断是否是超户或admin
      visible: false, // 模态框显示隐藏
      editObj: {}, // 编辑的数据
      isEdit: false, // 1. 编辑-true 2. 新增-false 3. 查看-check
    };
  }
  componentDidMount() {
    // 判断资管环境是否是超户或租户
    this.props.dispatch({
      type: 'BaselineInformationNewM/getUserInfo',
      payload: {},
      callback: (type, res) => {
        if (type == 'success') {
          this.setState(
            {
              currentUser: res,
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.getTableData();
        }
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 查询表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage } = this.state;
    this.props.dispatch({
      type: 'BaselineInformationNewM/getTableData',
      payload: {
        ...searchObj,
        page: {
          current: currentPage,
          pageSize: numInPage,
        },
      },
      callback: (type, data, columns) => {
        if (type == 'success') {
          this.setState({
            columns: columns,
            dataSource: data.dataSource,
            total: data.pageInfo.total,
          });
        }
      },
    });
  };
  //查询表格数据
  queryTableList = (e) => {
    this.setState(
      {
        searchObj: e,
        isReset: false,
        currentPage: 1,
        numInPage: 10,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 点击新增
  addClick = () => {
    this.setState({
      visible: true,
      isEdit: false,
    });
  };
  // 点击编辑
  onEditItem = (record) => {
    if (record) {
      let tempArr = [];
      if (record.children) {
        if (record.type == '复合') {
          record.children.map((item, index) => {
            if (item.benchId) {
              // 该条数据是自定义子基准
              tempArr.push({
                // key: index + 1,
                weight: Number((item.weight - 0) * 100).toFixed(2),
                benchId: item.benchId,
                wind: undefined,
              });
            } else {
              tempArr.push({
                // key: index + 1,
                weight: Number((item.weight - 0) * 100).toFixed(2),
                wind: item.wind,
                benchId: undefined,
              });
            }
          });
        } else if (record.type == '市值加权') {
          record.children.map((item, index) => {
            tempArr.push({
              // key: index + 1,
              weight: item.weight,
              wind: item.wind,
            });
          });
        }
      } else if (record.children === null) {
        tempArr.push({ weight: record.weight, wind: record.wind });
      }
      record.editDatas = tempArr;
    }
    this.setState({
      visible: true,
      isEdit: true,
      editObj: record,
    });
  };
  // 点击查看
  onCheckItem = (record) => {
    if (record) {
      let tempArr = [];
      if (record.children) {
        if (record.type == '复合') {
          record.children.map((item, index) => {
            if (item.benchId) {
              // 该条数据是自定义子基准
              tempArr.push({
                // key: index + 1,
                weight: Number((item.weight - 0) * 100).toFixed(2),
                benchId: item.benchId,
                wind: undefined,
              });
            } else {
              tempArr.push({
                // key: index + 1,
                weight: Number((item.weight - 0) * 100).toFixed(2),
                wind: item.wind,
                benchId: undefined,
              });
            }
          });
        } else if (record.type == '市值加权') {
          record.children.map((item, index) => {
            tempArr.push({
              // key: index + 1,
              weight: item.weight,
              wind: item.wind,
            });
          });
        }
      } else if (record.children === null) {
        tempArr.push({ weight: record.weight, wind: record.wind });
      }
      record.editDatas = tempArr;
    }
    this.setState({
      visible: true,
      isEdit: 'check',
      editObj: record,
    });
  };
  // 点击删除
  onDeleteItem = (record) => {
    const values = {
      benchId: record.benchId,
    };
    this.props.dispatch({
      type: 'BaselineInformationNewM/deleteOne',
      payload: values,
      callback: (res) => {
        if (res == 'success') {
          this.setState(
            {
              currentPage: 1,
              numInPage: 10,
            },
            () => {
              this.getTableData();
            },
          );
        }
      },
    });
  };
  // 模态框确认
  onModalOK = () => {
    const {
      form: { resetFields, validateFields, getFieldsValue },
    } = this.$operateForm.props;
    const { currentUser, isEdit, editObj } = this.state;
    const formValues = getFieldsValue();
    if (formValues.type == '市值加权') {
      if ((formValues.operator && !formValues.shift) || (!formValues.operator && formValues.shift)) {
        message.error('运算符与运算值需同时存在');
        return;
      }
    }
    validateFields((errors) => {
      if (errors) return;
      this.$operateForm.BenchInfoRef?.props.form.validateFields((err, benchFieldsValue) => {
        if (err) return;
        let benchData = benchFieldsValue.account;
        if (formValues.type == '单一') {
          benchData[0].weight = 1;
        } else if (formValues.type == '自定义' || formValues.type == '市值加权') {
          benchData.forEach((item) => {
            item.weight = null;
          });
        } else {
          // 复合
          benchData.forEach((item) => {
            item.weight = Number(item.weight / 100).toFixed(2);
          });
        }
        // if (errors) {

        //     console.log('444', benchFieldsValue);

        //     let flagFull = true
        //     let flagOne = true
        //     let SumWeight = 0
        //     let arrWind = []
        //     if (formValues.type == '复合') {
        //         formValues.benchComponents.forEach(item => {
        //             if (item.benchId) {
        //                 // 该条数据是自定义子基准
        //                 if ((!item.weight && item.weight !== 0) || !item.benchId) {
        //                     flagFull = false
        //                 } else {
        //                     if (item.weight === 0 || item.weight === 100) {
        //                         flagOne = false
        //                     }
        //                     SumWeight = SumWeight + item.weight
        //                     arrWind.push(item.wind)
        //                 }
        //             } else {
        //                 // 其他子基准
        //                 if ((!item.weight && item.weight !== 0) || !item.wind) {
        //                     flagFull = false
        //                 } else {
        //                     if (item.weight === 0 || item.weight === 100) {
        //                         flagOne = false
        //                     }
        //                     SumWeight = SumWeight + item.weight
        //                     arrWind.push(item.wind)
        //                 }
        //             }
        //         })
        //         if (flagFull) {
        //             if (!flagOne) {
        //                 message.error('复合类型子基准比例不能为0或100')
        //             } else if (SumWeight !== 100) {
        //                 message.error('子基准比例总和应为100')
        //             } else if (this.$operateForm.isRepeat(arrWind)) {
        //                 message.error('子基准不能重复!')
        //             }
        //         }
        //     } else if (formValues.type == '市值加权') {
        //         formValues.benchComponents?.forEach(item => {
        //             if (item.wind) {
        //                 arrWind.push(item.wind)
        //             } else {
        //                 flagFull = false
        //             }
        //         })
        //         if (flagFull) {
        //             if (this.$operateForm.isRepeat(arrWind)) {
        //                 message.error('子基准不能重复!')
        //             }
        //         }
        //     }
        //     return;
        // }
        // let tempComponents = []
        // if (formValues.type == '复合') {
        //     formValues.benchComponents?.forEach(item => {
        //         if (item.benchId) {
        //             // 该条数据是自定义子基准
        //             tempComponents.push({
        //                 weight: Number((item.weight - 0) / 100).toFixed(2),
        //                 benchId: item.benchId.split('【自定义】')[1],
        //             })
        //         } else {
        //             tempComponents.push({
        //                 weight: Number((item.weight - 0) / 100).toFixed(2),
        //                 wind: item.wind,
        //             })
        //         }

        //     })
        // } else {
        //     formValues.benchComponents?.forEach(item => {
        //         tempComponents.push({
        //             weight: item.weight, wind: item.wind
        //         })
        //     })
        // }
        if (!isEdit) {
          // 新增
          const modaldata = {
            benchName: formValues.benchName,
            operator: formValues.operator,
            shift: formValues.shift,
            type: formValues.type,
            benchLabel: formValues.benchLabel,
            createBy: currentUser.userId + '-' + currentUser.name,
            createTime: moment(),
            updateBy: currentUser.userId + '-' + currentUser.name,
            updateTime: moment(),
            // components: tempComponents
            components: benchData,
          };
          this.props.dispatch({
            type: 'BaselineInformationNewM/addOne',
            payload: {
              ...modaldata,
            },
            callback: (res) => {
              if (res == 'success') {
                this.setState({
                  visible: false,
                  editObj: {},
                });
                resetFields();
                this.getTableData();
              }
            },
          });
        } else if (isEdit == true) {
          // 编辑
          const modaldata = {
            benchId: editObj.benchId,
            benchName: formValues.benchName,
            operator: formValues.operator,
            shift: formValues.shift,
            type: formValues.type,
            benchLabel: formValues.benchLabel,
            updateBy: currentUser.userId + '-' + currentUser.name,
            updateTime: moment(),
            // components: tempComponents
            components: benchData,
          };
          this.props.dispatch({
            type: 'BaselineInformationNewM/updateOne',
            payload: {
              ...modaldata,
            },
            callback: (res) => {
              if (res == 'success') {
                this.setState({
                  visible: false,
                  editObj: {},
                });
                resetFields();
                this.getTableData();
              }
            },
          });
        }
      });
    });
  };
  // 模态框取消
  onCancel = () => {
    this.setState({
      visible: false,
      editObj: {},
    });
  };
  // 渲染table
  renderTable = () => {
    const { columns, dataSource, total, currentPage, numInPage } = this.state;
    if (columns.length && columns[columns.length - 1].title != '操作') {
      // 只有自己创建的才可以编辑
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record, index) => {
              this.onCheckItem(record);
            },
            rules: {
              hide: {
                items: [{ key: 'benchName', value: [undefined], relation: ['='] }],
              },
            },
          },
          {
            title: '编辑',
            onClick: (record, index) => {
              this.onEditItem(record);
            },
            rules: {
              hide: {
                items: [{ key: 'createBy', value: [this.state.currentUser.userId], relation: ['!='] }],
              },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.onDeleteItem(record);
            },
            rules: {
              hide: {
                items: [{ key: 'createBy', value: [this.state.currentUser.userId], relation: ['!='] }],
              },
            },
          },
        ],
      });
    }
    return (
      <TableC
        columns={columns}
        loading={this.props.loading.effects['BaselineInformationNewM/getTableData'] == true}
        dataSource={dataSource}
        current={currentPage}
        total={total}
        pageSize={numInPage}
        selfScrollY={true}
        rowKey='id'
        onChange={this.handleTableChange}
      />
    );
  };
  render() {
    const { selectBaselineType, visible, editObj, isEdit } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'keyWord',
          title: '基准名称',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
        {
          dataIndex: 'type',
          title: '基准类型',
          type: DATA_ENTRY.SELECT,
          dataSource: selectBaselineType,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='基准管理'
        contentHtml={
          <div>
            <div style={{ marginBottom: '10px' }}>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={this.addClick} />
            {this.renderTable()}
            {visible ? (
              <ModalC
                title={this.state.isEdit == true ? '编辑' : this.state.isEdit == 'check' ? '查看' : '新增'}
                visible={visible}
                maskClosable={false}
                onOk={this.onModalOK}
                onCancel={this.onCancel}
                footer={this.state.isEdit == 'check' ? null : undefined}
                width={580}
                confirmLoading={this.props.loading.effects['BaselineInformationNewM/addOne'] == true || this.props.loading.effects['BaselineInformationNewM/updateOne'] == true}
              >
                <OperateForm
                  editObj={editObj}
                  isEdit={isEdit}
                  onRef={(ref) => {
                    this.$operateForm = ref;
                  }}
                />
              </ModalC>
            ) : (
              ''
            )}
          </div>
        }
      />
    );
  }
}
